<template>
  <div class="media-list-container">
    <!-- 查询条件卡片 -->
    <el-card class="search-card">
      <template #header>
        <div class="card-header">
          <span>媒体查询</span>
        </div>
      </template>
      
      <el-form :inline="true" :model="searchForm">
        <el-form-item label="媒体">
          <el-select v-model="searchForm.mediaId" placeholder="请选择媒体" clearable filterable>
            <el-option
              v-for="media in mediaOptions"
              :key="media.id"
              :label="media.name"
              :value="media.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon>
            查询
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 数据表格卡片 -->
    <el-card class="table-card">
      <template #header>
        <div class="card-header">
          <span>媒体列表</span>
          <el-button type="primary" @click="handleAdd">
            <el-icon><Plus /></el-icon>
            新增媒体
          </el-button>
        </div>
      </template>

      <el-table
        :data="mediaList"
        style="width: 100%"
        v-loading="loading"
      >
        <el-table-column prop="id" label="ID" width="180" />
        <el-table-column prop="name" label="媒体名称" min-width="200" />
        <el-table-column prop="aesKey" label="AES-KEY" min-width="200">
          <template #default="{ row }">
            <el-tooltip v-if="row.aesKey" :content="row.aesKey" placement="top">
              <el-tag type="warning">
                {{ row.aesKey ? '已设置' : '未设置' }}
              </el-tag>
            </el-tooltip>
            <el-tag v-else type="info">
              未设置
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="mediaCostRate" label="成本率" width="100">
          <template #default="{ row }">
            <el-tag type="info">
              {{ row.mediaCostRate || '未设置' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="row.status === 'active' ? 'success' : 'danger'">
              {{ row.status === 'active' ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="osType" label="系统类型" width="100">
          <template #default="{ row }">
            <el-tag type="info">
              {{ row.osType === '1' ? 'Android' : row.osType === '2' ? 'iOS' : 'Unknown' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createdAt" label="创建时间" width="180" />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" size="small" @click="handleEdit(row)">
              <el-icon><Edit /></el-icon>
              编辑
            </el-button>
            <el-button 
              type="warning" 
              size="small" 
              @click="handleEditCostRate(row)"
            >
              <el-icon><Edit /></el-icon>
              成本率
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :total="pagination.total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :hide-on-single-page="false"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 新增/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="500px"
    >
      <el-form
        ref="mediaFormRef"
        :model="mediaForm"
        :rules="mediaRules"
        label-width="80px"
      >
        <el-form-item label="媒体名称" prop="name">
          <el-input v-model="mediaForm.name" placeholder="请输入媒体名称" />
        </el-form-item>
        <el-form-item label="AES-KEY" prop="aesKey">
          <el-input v-model="mediaForm.aesKey" placeholder="请输入AES-KEY" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="mediaForm.status">
            <el-radio value="active">启用</el-radio>
            <el-radio value="inactive">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 成本率修改对话框 -->
    <el-dialog
      v-model="costRateDialogVisible"
      title="修改成本率"
      width="400px"
    >
      <el-form label-width="80px">
        <el-form-item label="媒体名称">
          <el-input v-model="costRateForm.name" readonly />
        </el-form-item>
        <el-form-item label="成本率">
          <el-input-number
            v-model="costRateForm.costRate"
            :min="0"
            :max="100"
            :precision="2"
            :step="0.01"
            controls-position="right"
            style="width: 100%"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="costRateDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleUpdateCostRate">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { FormInstance, FormRules, UploadFile, UploadFiles } from 'element-plus'
import { InfoFilled } from '@element-plus/icons-vue'
import { fetchMediaData, updateMediaCostRate, type ApiMediaItem, type ApiResponse } from '@/api/media'

// 前端使用的媒体项接口
interface MediaItem {
  id: string
  name: string
  aesKey: string | null
  status: string
  createdAt: string
  osType: string
  mediaCostRate: number | null
}

interface SearchForm {
  mediaId: string
  status: string
}

interface MediaOption {
  id: string
  name: string
}

interface MediaForm {
  id?: string
  name: string
  aesKey?: string
  status: string
}

const loading = ref(false)
const dialogVisible = ref(false)
const dialogTitle = ref('新增媒体')
const mediaFormRef = ref<FormInstance>()
const fileList = ref<UploadFile[]>([])

// 成本率修改相关变量
const costRateDialogVisible = ref(false)
const costRateForm = reactive({
  id: '',
  name: '',
  costRate: 0
})

const searchForm = reactive<SearchForm>({
  mediaId: '',
  status: ''
})

const mediaForm = reactive<MediaForm>({
  name: '',
  aesKey: '',
  status: 'active'
})

const mediaRules: FormRules = {
  name: [{ required: true, message: '请输入媒体名称', trigger: 'blur' }],
  aesKey: [{ required: false, message: '请输入AES-KEY', trigger: 'blur' }],
  status: [{ required: true, message: '请选择状态', trigger: 'change' }]
}

const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

const mediaList = ref<MediaItem[]>([])
const mediaOptions = ref<MediaOption[]>([])

// 转换API数据到前端格式
const transformApiData = (apiData: ApiMediaItem[]): MediaItem[] => {
  return apiData.map(item => ({
    id: item.id,
    name: item.name,
    aesKey: item.aesKey,
    status: 'active', // API没有返回状态，设为默认值
    createdAt: item.createTime,
    osType: item.osType,
    mediaCostRate: item.mediaCostRate
  }))
}

const getTypeColor = (type: string) => {
  const colorMap: Record<string, string> = {
    image: 'primary',
    video: 'success',
    audio: 'warning',
    document: 'info'
  }
  return colorMap[type] || 'default'
}

const getTypeLabel = (type: string) => {
  const labelMap: Record<string, string> = {
    image: '图片',
    video: '视频',
    audio: '音频',
    document: '文档'
  }
  return labelMap[type] || type
}

const formatFileSize = (bytes: number) => {
  if (bytes === 0) return '0 Bytes'
  const k = 1024
  const sizes = ['Bytes', 'KB', 'MB', 'GB']
  const i = Math.floor(Math.log(bytes) / Math.log(k))
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
}

// 加载媒体选项数据
const loadMediaOptions = async () => {
  try {
    const params = {
      current: 1,
      size: 1000 // 获取所有媒体数据
    }
    
    const response = await fetchMediaData(params)
    mediaOptions.value = response.records.map(item => ({
      id: item.id,
      name: item.name
    }))
  } catch (error) {
    console.error('加载媒体选项失败:', error)
  }
}

const loadData = async () => {
  loading.value = true
  try {
    // 构建API请求参数
    const params = {
      current: pagination.currentPage,
      size: pagination.pageSize,
      id: searchForm.mediaId || undefined,
      // 注意：API没有type和status字段，这些筛选将在前端进行
    }
    
    const response = await fetchMediaData(params)
    
    // 转换API数据到前端格式
    const transformedData = transformApiData(response.records)
    
    // 前端筛选（因为API不支持这些字段的筛选）
    let filteredData = transformedData
    if (searchForm.status) {
      filteredData = filteredData.filter(item => item.status === searchForm.status)
    }
    
    mediaList.value = filteredData
    pagination.total = response.totalRow
    
  } catch (error) {
    ElMessage.error('获取媒体数据失败，请稍后重试')
    console.error('加载数据失败:', error)
  } finally {
    loading.value = false
  }
}

const handleSearch = () => {
  pagination.currentPage = 1
  loadData()
}

const handleReset = () => {
  searchForm.mediaId = ''
  searchForm.status = ''
  handleSearch()
}

// 打开成本率修改弹窗
const handleEditCostRate = (row: MediaItem) => {
  costRateForm.id = row.id
  costRateForm.name = row.name
  costRateForm.costRate = row.mediaCostRate || 0
  costRateDialogVisible.value = true
}

// 更新成本率
const handleUpdateCostRate = async () => {
  try {
    await updateMediaCostRate(costRateForm.id, costRateForm.costRate)
    ElMessage.success('成本率更新成功')
    costRateDialogVisible.value = false
    // 刷新数据
    await loadData()
  } catch (error) {
    console.error('更新成本率失败:', error)
    ElMessage.error('成本率更新失败')
  }
}

const handleSizeChange = (val: number) => {
  pagination.pageSize = val
  loadData()
}

const handleCurrentChange = (val: number) => {
  pagination.currentPage = val
  loadData()
}

const handleAdd = () => {
  dialogTitle.value = '新增媒体'
  mediaForm.id = undefined
  mediaForm.name = ''
  mediaForm.aesKey = ''
  mediaForm.status = 'active'
  dialogVisible.value = true
}

const handleEdit = (row: MediaItem) => {
  dialogTitle.value = '编辑媒体'
  mediaForm.id = row.id
  mediaForm.name = row.name
  mediaForm.aesKey = row.aesKey || ''
  mediaForm.status = row.status
  dialogVisible.value = true
}

const handleToggleStatus = (row: MediaItem) => {
  const action = row.status === 'active' ? '禁用' : '启用'
  ElMessageBox.confirm(
    `确定要${action}媒体 "${row.name}" 吗？`,
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    row.status = row.status === 'active' ? 'inactive' : 'active'
    ElMessage.success(`${action}成功`)
  })
}



const handleSubmit = async () => {
  if (!mediaFormRef.value) return
  
  await mediaFormRef.value.validate((valid) => {
    if (valid) {
      // 由于API接口限制，这里仅做前端模拟
      // 实际项目中应该调用相应的API接口
      if (mediaForm.id) {
        // 编辑模式 - 更新本地数据
        const index = mediaList.value.findIndex(item => item.id === mediaForm.id)
        if (index !== -1) {
          mediaList.value[index] = {
            ...mediaList.value[index],
            name: mediaForm.name,
            aesKey: mediaForm.aesKey || null,
            status: mediaForm.status
            // 保持原有的osType和其他字段不变
          }
        }
        ElMessage.success('编辑成功')
      } else {
        // 新增模式 - 添加到本地数据
        const newMedia: MediaItem = {
          id: Date.now().toString(),
          name: mediaForm.name,
          aesKey: mediaForm.aesKey || null,
          status: mediaForm.status,
          createdAt: new Date().toISOString(),
          osType: '1' // 默认设置为Android
        }
        mediaList.value.unshift(newMedia)
        pagination.total++
        ElMessage.success('新增成功')
      }
      dialogVisible.value = false
      // 重新加载数据以确保一致性
      loadData()
    }
  })
}

onMounted(async () => {
  // 加载媒体选项数据
  await loadMediaOptions()
  // 加载媒体列表数据
  await loadData()
})
</script>

<style scoped>
.media-list-container {
  padding: 20px;
  min-height: calc(100vh - 60px); /* 减去顶部导航栏高度 */
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-weight: 600;
  color: #2c3e50;
  font-size: 16px;
}

.search-card {
  margin-bottom: 20px;
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
  border: 1px solid rgba(255, 255, 255, 0.2);
  border-radius: 16px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
}

.table-card {
  margin-top: 20px;
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
  border: 1px solid rgba(255, 255, 255, 0.2);
  border-radius: 16px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.upload-demo {
  width: 100%;
}

:deep(.el-upload-dragger) {
  width: 100%;
}

/* 按钮样式 */
.el-button {
  border-radius: 8px;
  transition: all 0.3s ease;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.el-button:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.el-button--primary {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border: none;
}

.el-button--primary:hover {
  background: linear-gradient(135deg, #5a6fd8 0%, #6a4190 100%);
}

/* 表单元素样式 */
:deep(.el-input__wrapper),
:deep(.el-select__wrapper),
:deep(.el-input-number__wrapper) {
  border-radius: 8px;
  border: 1px solid rgba(102, 126, 234, 0.2);
  background: rgba(255, 255, 255, 0.9);
  transition: all 0.3s ease;
}

:deep(.el-input__wrapper:hover),
:deep(.el-select__wrapper:hover),
:deep(.el-input-number__wrapper:hover) {
  border-color: rgba(102, 126, 234, 0.4);
  box-shadow: 0 2px 8px rgba(102, 126, 234, 0.1);
}

:deep(.el-input__wrapper.is-focus),
:deep(.el-select__wrapper.is-focus) {
  border-color: #667eea;
  box-shadow: 0 0 0 2px rgba(102, 126, 234, 0.2);
  transform: translateY(-1px);
}

/* 表格样式 */
:deep(.el-table) {
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
}

:deep(.el-table__header-wrapper) {
  border-radius: 12px 12px 0 0;
  overflow: hidden;
}

:deep(.el-table th) {
  font-weight: 600;
  border: none;
}

:deep(.el-table th.el-table__cell) {
  background-color: transparent;
}

/* 分页样式 */
.pagination-container {
  margin-top: 24px;
  display: flex;
  justify-content: center;
}

:deep(.el-pagination) {
  justify-content: center;
}

:deep(.el-pagination .el-pager li) {
  color: #2c3e50;
  font-weight: 500;
}

:deep(.el-pagination .el-pager li.active) {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: #ffffff;
  border-radius: 4px;
}

/* 动画效果 */
@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

@keyframes slideInUp {
  from {
    opacity: 0;
    transform: translateY(30px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

@keyframes pulse {
  0%, 100% {
    transform: scale(1);
  }
  50% {
    transform: scale(1.05);
  }
}

.media-list-container {
  animation: fadeIn 0.6s ease-out;
}

.search-card {
  animation: slideInUp 0.6s ease-out;
}

.table-card {
  animation: slideInUp 0.8s ease-out;
}
</style>